/*
 * Copyright (C) 2008 Chris Bellew
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "iDynDNSd.h";
#import "iDynDNSController.h";
#import "iDynDNSSettingsView.h";

#include <unistd.h>
#include <signal.h>
#include <kvm.h>
#include <fcntl.h>
#include <sys/sysctl.h>
#include <sys/types.h>



#define LAUNCHD_FILE @"/Library/LaunchDaemons/com.bantha-fodder.idyndnsd.plist"


//From Nate True's dock application:
pid_t springboard_pid() {
	uint32_t	    i;
    size_t			length;
	int32_t			err, count;
    struct kinfo_proc	   *process_buffer;
    struct kinfo_proc      *kp;
    int				mib[ 3 ] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL };
    pid_t           spring_pid;
    int             loop, argmax;

    spring_pid = -1;

	sysctl( mib, 3, NULL, &length, NULL, 0 );

    if (length == 0)
        return -1;
	
	process_buffer = (struct kinfo_proc *)malloc(length);

    for ( i = 0; i < 60; ++i ) {
        // in the event of inordinate system load, transient sysctl() failures are
        // possible.  retry for up to one minute if necessary.
        if ( ! ( err = sysctl( mib, 3, process_buffer, &length, NULL, 0 ) ) ) break;
        sleep( 1 );
    }	

    if (err) {
        free(process_buffer);
        return -1;
    }
        
    count = length / sizeof(struct kinfo_proc);

    kp = process_buffer;

#ifdef DEBUG
    fprintf(stderr,"PID scan: found %d visible procs\n", count);
#endif            

    for (loop = 0; (loop < count) && (spring_pid == -1); loop++) {
#ifdef DEBUG
        fprintf(stderr,"PID: checking process %d (%s)\n", kp->kp_proc.p_pid, kp->kp_proc.p_comm);
#endif              

        if (!strcasecmp(kp->kp_proc.p_comm,"SpringBoard")) {
            spring_pid = kp->kp_proc.p_pid;
        }
        kp++;
    }

    free(process_buffer);
    
    return spring_pid;
}

uid_t springboard_uid() {
	uint32_t	    i;
	size_t			length;
	int32_t			err, count;
	struct kinfo_proc	   *process_buffer;
	struct kinfo_proc      *kp;
	int				mib[ 3 ] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL };
	uid_t           spring_uid;
	int             loop;
	
	spring_uid = -1;
	
	sysctl( mib, 3, NULL, &length, NULL, 0 );
	
	if (length == 0)
		return -1;
	
	process_buffer = (struct kinfo_proc *)malloc(length);
	
	for ( i = 0; i < 60; ++i ) {
		// in the event of inordinate system load, transient sysctl() failures are
		// possible.  retry for up to one minute if necessary.
		if ( ! ( err = sysctl( mib, 3, process_buffer, &length, NULL, 0 ) ) ) break;
		sleep( 1 );
	}	
	
	if (err) {
		free(process_buffer);
		return -1;
	}
	
	count = length / sizeof(struct kinfo_proc);
	
	kp = process_buffer;
	
	for (loop = 0; (loop < count) && (spring_uid == -1); loop++) {
		if (!strcasecmp(kp->kp_proc.p_comm,"SpringBoard")) {
			spring_uid = kp->kp_eproc.e_pcred.p_ruid;
		}
		kp++;
	}
	
	free(process_buffer);
	
	return spring_uid;
}

UIApplication *theApp = NULL;


void removeIcon(int status) {
	if(theApp != NULL) {
		NSLog(@"removing icon");
		[theApp removeStatusBarImageNamed: @"iDynDNS"];
	}
	exit(0);
}

int main(int argc, char **argv)
{
	struct sigaction sa;
	sa.sa_handler = removeIcon;
	
	sigaction(SIGTERM,  &sa, NULL);	
	
	//Give SpringBoard time to start up
	while(springboard_pid() == -1) {
		sleep(4);
	}
	
	setuid(springboard_uid());
	sleep(2);
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	int ret = UIApplicationMain(argc, argv, [iDynDNSd class]);
	[pool release];
	return ret;
} 


